package com.sviet.game.tetriswindow.database;

import java.util.ArrayList;
import java.util.List;

import com.sviet.game.tetriswindow.data.Score;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public class ScoreDao extends BaseDao {
	public final static String TAG = "ScoreDao";

	public static final String TABLE_NAME = "tb_score";
	
	// table field
	public static final String ID_COL = "id";
	public static final String PLAY_NAME_COL = "play_name";
	public static final String NUMBER_LINE_COL = "number_line";
	public static final String SCORE_COL = "score";

	public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME
			+ "(" 
				+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ PLAY_NAME_COL + " TEXT ," 
				+ NUMBER_LINE_COL + " INTEGER ," 
				+ SCORE_COL + " INTEGER ,"
			+ ");";

	private static final String[] COLUMNS = { ID_COL,
		PLAY_NAME_COL, NUMBER_LINE_COL, SCORE_COL};

	public ScoreDao(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public long insert(Score score) {
		ContentValues values = new ContentValues();
		values.put(ID_COL, score.getId());
		values.put(PLAY_NAME_COL, score.getPlay_name());
		values.put(NUMBER_LINE_COL, score.getNumber_line());
		values.put(SCORE_COL, score.getScore());
		return db.insert(TABLE_NAME, null, values);
	}

	public long update(Score score) {
		ContentValues values = new ContentValues();
		values.put(ID_COL, score.getId());
		values.put(PLAY_NAME_COL, score.getPlay_name());
		values.put(NUMBER_LINE_COL, score.getNumber_line());
		values.put(SCORE_COL, score.getScore());
		
		return db.update(TABLE_NAME, values, ID_COL + " = ? ",
				new String[] { String.valueOf(score.getId()) });
	}

	public int deleteById(int id) {
		String whereClause = ID_COL + " = " + id;

		return db.delete(TABLE_NAME, whereClause, null);
	}

	public List<Score> GetAllComic() {
		// TODO Auto-generated method stub
		List<Score> list = new ArrayList<Score>();
		Cursor cursor = db.query(TABLE_NAME, COLUMNS, null, null, null,
				null, SCORE_COL);
		// Cursor cursor = db.query(TABLE_NAME, COLUMNS, null, null, null, null,
		// ENTRY_ID);

		try {
			while (cursor.moveToNext()) {

				list.add(getComic(cursor));
			}
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return list;
	}

	private Score getComic(Cursor cursor) {
		// TODO Auto-generated method stub
		int columnIndex = 1;
		Score score = new Score(cursor.getInt(columnIndex ++),
				cursor.getString(columnIndex++), cursor.getInt(columnIndex ++),
				cursor.getInt(columnIndex ++));
		
		return score;
	}
}
